<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <!--表单组件-->
      <el-dialog :close-on-click-modal="false" v-model="addDialog" :title="title" width="680px">
        <el-form ref="formData" :model="formData" :rules="rules" label-width="80px">
          <el-form-item label="版本名称" prop="versionName">
            <el-input v-model="formData.versionName" style="width: 370px" />
          </el-form-item>

          <el-form-item label="设备类型">
            <el-select v-model="formData.deviceTypeId" clearable placeholder="请选择" size="small">
              <el-option
                v-for="item in deviceTypeList"
                :key="item.id"
                :label="item.deviceTypeName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="APP版本号" prop="version">
            <el-input v-model="formData.version" style="width: 370px" />
          </el-form-item>
          <el-form-item label="文件上传">
            <el-upload
              ref="upload"
              :limit="1"
              accept=".APK,.apk"
              :headers="upload.headers"
              :action="upload.url + '/sys/device/version/updateApk'"
              :on-progress="handleFileUploadProgress"
              :on-success="handleFileSuccess"
              :auto-upload="true"
              drag
            >
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              <template #tip>
                <div class="el-upload__tip">只能上传APK文件，且不超过50,000 KB</div>
              </template>
            </el-upload>
          </el-form-item>

          <el-form-item label="更新说明" prop="remark">
            <el-input type="textarea" v-model="formData.remark" />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="addDialog = false">取消</el-button>
            <el-button type="primary" @click="submitForm">确认</el-button>
          </div>
        </template>
      </el-dialog>

      <el-dialog
        :close-on-click-modal="false"
        v-model="examineDialog"
        title="APK审核"
        width="680px"
      >
        <el-form
          ref="formExamineData"
          :model="formExamineData"
          :rules="ExamineRules"
          label-width="80px"
        >
          <el-form-item label="文件名称" prop="versionName">
            <el-input v-model="formExamineData.versionName" style="width: 370px" readonly />
          </el-form-item>

          <el-form-item label="原文件名称" prop="fileName">
            <el-input v-model="formExamineData.fileName" style="width: 370px" readonly />
          </el-form-item>

          <el-form-item label="设备类型" prop="deviceTypeName">
            <el-input v-model="formExamineData.deviceTypeName" style="width: 370px" readonly />
          </el-form-item>

          <el-form-item label="APP版本号" prop="version">
            <el-input v-model="formExamineData.version" style="width: 370px" readonly />
          </el-form-item>

          <el-form-item label="APK文件下载地址" prop="apkUrl">
            <el-input v-model="formExamineData.apkUrl" readonly />
          </el-form-item>

          <el-form-item label="状态" prop="isStatus">
            <el-select
              v-model="formExamineData.isStatus"
              clearable
              placeholder="请选择"
              size="small"
            >
              <el-option
                v-if="
                  formExamineData.isStatus == 'UNDER_REVIEW' ||
                  formExamineData.isStatus == 'AUDIT_FAILED'
                "
                label="审核中"
                value="UNDER_REVIEW"
              />
              <el-option
                v-if="
                  formExamineData.isStatus == 'UNDER_REVIEW' ||
                  formExamineData.isStatus == 'APPROVED'
                "
                label="审核通过"
                value="APPROVED"
              />
              <el-option
                v-if="formExamineData.isStatus == 'UNDER_REVIEW'"
                label="审核失败"
                value="AUDIT_FAILED"
              />
              <el-option
                v-if="
                  formExamineData.isStatus == 'SHELVES' ||
                  formExamineData.isStatus == 'OFF_THE_SHELF' ||
                  formExamineData.isStatus == 'APPROVED'
                "
                label="上架"
                value="SHELVES"
              />
              <el-option
                v-if="
                  formExamineData.isStatus == 'SHELVES' ||
                  formExamineData.isStatus == 'OFF_THE_SHELF' ||
                  formExamineData.isStatus == 'APPROVED'
                "
                label="下架"
                value="OFF_THE_SHELF"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="更新说明" prop="remark">
            <el-input type="textarea" v-model="formExamineData.remark" />
          </el-form-item>
        </el-form>
        <div>
          <div class="dialog-footer">
            <el-button @click="examineDialog = false">取消</el-button>
            <el-button type="primary" @click="submitFormExamine">确认</el-button>
          </div>
        </div>
      </el-dialog>

      <div>
        <el-button type="success" round icon="el-icon-plus" @click="uploadApk"
          >上传APK文件</el-button
        >
      </div>

      <el-tabs v-model="activeName" type="card" @tab-click="handleClick" style="margin-top: 5px">
        <el-tab-pane label="兑币机" name="3" />
        <el-tab-pane label="闸机" name="7" />
        <el-tab-pane label="POS机" name="6" />
        <el-tab-pane label="彩票机" name="5" />
        <el-tab-pane label="存币机" name="4" />
        <el-tab-pane label="票务机" name="11" />
      </el-tabs>

      <!--表格渲染-->
      <el-table
        ref="table"
        v-loading="loading"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        :data="deviceVersionList"
        row-key="id"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="版本名称" prop="versionName" />
        <el-table-column label="原文件名称" prop="fileName" />
        <el-table-column label="文件版本号" prop="version" />
        <el-table-column label="状态" prop="isStatus">
          <template #default="scope">
            {{
              formatDictMap('APK_STATUS_LIST').find((item) => item.value == scope.row.isStatus)
                .label
            }}
          </template>
        </el-table-column>
        <el-table-column label="版本说明" prop="remark" :show-overflow-tooltip="true" width="200" />
        <el-table-column label="创建时间" prop="createTime" />
        <el-table-column label="创建人" prop="createBy" />
        <el-table-column label="操作" width="260px" fixed="right">
          <template #default="scope">
            <el-button @click="handleDownload(scope.row)">APK下载</el-button>

            <el-button @click="handleDetails(scope.row)">审核或上架</el-button>

            <el-button @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
  import { deviceTypeList } from '@/api/device/type.js';
  import { getDictOptions } from '@/utils/dict';
  import {
    deviceVersionList,
    deviceVersionDetails,
    deviceVersionDelete,
    deviceVersionUpdate,
    deviceVersionSave,
    deviceVersionDownload,
    deviceVersionApproval,
  } from '@/api/device/version';
  import { getToken } from '@/utils/auth';

  export default {
    name: 'DeviceVersionList',
    dicts: ['APK_STATUS_LIST'],
    data() {
      return {
        key: '',
        loading: false,
        upload: {
          // 设置上传的请求头部
          headers: { Authorization: 'Bearer ' + getToken() },
          // 上传的地址
          url: '/prod-api',
        },

        activeName: '3',
        single: true,
        multiple: true,
        tableDataList: [],
        addDialog: false,
        examineDialog: false,
        title: '上传Apk文件',
        form: {},
        total: 0,
        numCode: '',
        page: {
          pageNum: 1, // 当前页数
          pageSize: 10, // 每页显示多少条
        },
        formData: {},
        formExamineData: {},
        rules: {
          versionName: [{ required: true, message: '设备版本名称不可为空', trigger: 'blur' }],
          deviceTypeId: [{ required: true, message: '设备类型不可为空', trigger: 'blur' }],
          version: [{ required: true, message: '设备版本号不可为空', trigger: 'blur' }],
          remark: [{ required: true, message: '更新说明不可为空', trigger: 'blur' }],
        },
        ExamineRules: {
          remark: [{ required: true, message: '审核说明不可为空', trigger: 'blur' }],
        },
        deviceTypeList: [],
        deviceVersionList: [],
        deviceVersion: {},
        fileList: [],
      };
    },
    created() {
      this.getList('3');
      this.getDeviceTypeList();
    },
    methods: {
      // 格式化字典
      formatDictMap(dictEnum) {
        return getDictOptions(dictEnum);
      },
      /** 转换菜单数据结构 */
      normalizer(node) {
        if (node.children && !node.children.length) {
          delete node.children;
        }
        return {
          id: node.id,
          label: node.deviceTypeName,
          children: node.children,
        };
      },
      // 提交表单
      submitForm() {
        this.$refs['formData'].validate((valid) => {
          if (valid) {
            if (this.formData.id) {
              deviceVersionUpdate(this.formData).then(() => {
                this.$modal.msgSuccess('修改成功');
                this.addDialog = false;
                this.getList(this.activeName);
              });
            } else {
              // 保存商品分类
              deviceVersionSave(this.formData).then(() => {
                this.$modal.msgSuccess('新增成功');
                this.addDialog = false;
                this.getList(this.activeName);
              });
            }
            this.reset();
          }
        });
      },
      // 表单重置
      reset() {
        this.formData = {
          versionName: undefined,
          deviceTypeId: undefined,
          id: undefined,
          version: undefined,
          numCode: undefined,
        };
      },
      /** 查询设备版本信息 */
      getList(deviceTypeId) {
        this.loading = true;
        console.log(deviceTypeId);
        deviceVersionList(deviceTypeId).then((res) => {
          this.deviceVersionList = res;
          this.loading = false;
        });
      },
      // 查询设备类型列表
      getDeviceTypeList() {
        deviceTypeList({}).then((res) => {
          this.deviceTypeList = res;
        });
      },

      // 文件上传成功处理
      handleFileSuccess(response) {
        if (response) {
          this.numCode = response;
          this.formData.numCode = response;
        }
      },
      // 文件上传中处理
      handleFileUploadProgress() {
        this.upload.isUploading = true;
      },
      handleClick(tab, event) {
        console.log(tab);
        console.log(tab.props.name);
        console.log(event);
        this.getList(tab.props.name);
      },
      //apk下载
      handleDownload(row) {
        const id = row.id;
        deviceVersionDownload(id).then((res) => {
          if (res) {
            window.location.href = res.data;
          } else {
            this.$modal.msgError(res.msg);
          }
        });
      },
      //版本删除
      handleDelete(row) {
        const id = row.id;
        this.$modal
          .confirm('是否确认删除设备版本，删除后不可恢复？')
          .then(function () {
            return deviceVersionDelete(id);
          })
          .then(() => {
            this.getList(this.activeName);
            this.$modal.msgSuccess('删除成功');
          })
          .catch(() => {});
      },
      handleDetails(row) {
        const id = row.id;
        this.examineDialog = true;
        deviceVersionDetails(id).then((res) => {
          if (res.code === 200) {
            this.formExamineData = res.data;
          } else {
            this.$modal.msgError(res.msg);
          }
        });
      },
      submitFormExamine() {
        this.$refs['formExamineData'].validate((valid) => {
          if (valid) {
            deviceVersionApproval(this.formExamineData).then(() => {
              this.$modal.msgSuccess('修改成功');
              this.examineDialog = false;
              this.getList(this.activeName);
            });
            this.reset();
          }
        });
      },
      uploadApk() {
        const size = this.deviceVersionList.length;
        if (size >= 10) {
          this.$modal.msgError('仅上传10个APK文件！');
        } else {
          this.addDialog = true;
        }
      },
    },
  };
</script>

<style scoped></style>
